using System;
using System.Text;
using System.Web;
using System.Linq;

namespace CavemanTools.Web
{
	public static class WebExtensions
	{
		/// <summary>
		/// Gets the IP of the user  detects proxy
		/// </summary>
		/// <param name="request"></param>
		/// <returns></returns>
		public static string RealIp(this HttpRequest request)
		{
			if (request == null) throw new ArgumentNullException("request");
			var fip = request.ServerVariables["HTTP_X_FORWARDED_FOR"];
			if ( fip!= null)
			{
				var ip = fip.Split(',').LastOrDefault();
				if (!string.IsNullOrEmpty(ip)) return ip.Trim();				
			}
			return request.UserHostAddress;
		}

		/// <summary>
		///  Returns subdomain from url
		/// </summary>
		/// <exception cref="ArgumentNullException"></exception>
		/// <param name="host">Host name</param>
		/// <returns></returns>
		public static string ExtractSubdomain(this string  host)
		{
			if (string.IsNullOrEmpty(host)) throw new ArgumentNullException("host");
			var all = host.Split('.');
			if (all.Length < 3) return string.Empty;
			var l = all.Length - 3;
			string d = string.Empty;
			for (int i = 0; i <= l; i++) d = d + all[i]+".";
			return d.Remove(d.Length-1,1);
		}

		/// <summary>
		/// Creates url friendly slug of a string
		/// </summary>
		/// <param name="text"></param>
		/// <returns></returns>
		public static string MakeSlug(this string text)
		{
			if (string.IsNullOrEmpty(text)) return string.Empty;
			
			// to lowercase, trim extra spaces
			text = text.ToLower().Trim();

			var len = text.Length;
			var sb = new StringBuilder(len);
			bool prevdash = false;
			char c;

			for (int i = 0; i < text.Length; i++)
			{
				c = text[i];
				if (c == ' ' || c == ',' || c == '.' || c == '/' || c == '\\' || c == '-')
				{
					if (!prevdash)
					{
						sb.Append('-');
						prevdash = true;
					}
				}
				else if ((c >= 'a' && c <= 'z') || (c >= '0' && c <= '9'))
				{
					sb.Append(c);
					prevdash = false;
				}
				if (i == 80) break;
			}

			text = sb.ToString();
			// remove trailing dash, if there is one
			if (text.EndsWith("-"))
				text = text.Substring(0, text.Length - 1);
			return text;
		}
	}
}